/**
* project3D Engine
* @author John Sword
* @version 2 - AS3
*/

package engine.materials
{
	
	import engine.materials.Material;
	import engine.geom.Face;
	import flash.display.Sprite;
	import flash.display.Graphics;
	import flash.geom.Matrix;
	
	public class ZLighten extends Material
	{
		
		public function ZLighten ()
		{
			super( null );
		}
		
		public override function render ( face:Face, screen:Sprite ) : void
		{
			// get vertices x,y positions
			var verts:Array = new Array ( 3 );
			verts.push( face.v1 );
			verts.push( face.v2 );
			verts.push( face.v3 );
			//var verts:Array = face.vertices;
			
			var g:Graphics = screen.graphics;

			var zsort:Array = verts.sortOn("z", Array.NUMERIC | Array.RETURNINDEXEDARRAY);
			
			var v0:Object = verts[zsort[0]];
			var v1:Object = verts[zsort[1]];
			var v2:Object = verts[zsort[2]];
			
			/*
			var x0:Number = v0.x;
			var y0:Number = v0.y;
			var x1:Number = v1.x;
			var y1:Number = v1.y;
			var x2:Number = v2.x;
			var y2:Number = v2.y;
			var z0:Number = v0.z;
			var z1:Number = v1.z;
			var z2:Number = v2.z;
			*/
			
			var x0:Number = v0.screen.x;
			var y0:Number = v0.screen.y;
			var x1:Number = v1.screen.x;
			var y1:Number = v1.screen.y;
			var x2:Number = v2.screen.x;
			var y2:Number = v2.screen.y;
			var z0:Number = v0.z;
			var z1:Number = v1.z;
			var z2:Number = v2.z;

			var zMin:Number = -300;
			var zMax:Number = 300;
			var zRange:Number = zMax - zMin;
			
			// build deltas
			var aa:Number = x1 - x0;
			var bb:Number = y1 - y0;
			var cc:Number = z1 - z0;
			var dd:Number = x2 - x0;
			var ee:Number = y2 - y0;
			var ff:Number = z2 - z0;
			var n1:Number = bb * ff - cc * ee;
			var n2:Number = cc * dd - aa * ff;
			var n3:Number = aa * ee - bb * dd;
			var nlen:Number = Math.sqrt(n1 * n1 + n2 * n2 + n3 * n3);
			var sx:Number = n1 / nlen;
			var sy:Number = n2 / nlen;

			//var col1:Number = 255 - (z0 - zMin) / zRange * 255;
			//var col2:Number = 255 - (z2 - zMin) / zRange * 255;
			var col1:Number = 255 - z0 / zRange * 10;
			var col2:Number = 255 - z2 / zRange * 10;

			var dx:Number = x2 - x0;
			var dy:Number = y2 - y0;
			var dist:Number = sx * dx + sy * dy;
			var wh:Number = dist * 2;

			var matrix:Matrix = new Matrix();

			matrix.createGradientBox(wh, wh, Math.atan2(sy, sx), x0 - dist, y0 - dist);
			g.lineStyle( wireSize, wireColor, wireAlpha);
			g.beginGradientFill("linear", [col1 << 16 | col1 << 8 | col1, col2 << 16 | col2 << 8 | col2], [100, 100], [128, 255], matrix);
			
			x0 = v0.screen.x;
			y0 = v0.screen.y;
			x1 = v1.screen.x;
			y1 = v1.screen.y;
			x2 = v2.screen.x;
			y2 = v2.screen.y;
			
			g.moveTo(x0, y0);
			g.lineTo(x1, y1);
			g.lineTo(x2, y2);
			g.endFill();
		}
		
	}
	
}
